/**
 * 初始化通知详情对话框
 */
var NoticeInfoDlg = {
    noticeInfoData: {},
    editor: null,
    validateFields: {
        title: {
            validators: {
                notEmpty: {
                    message: '标题不能为空'
                }
            }
        }
    }
};

/**
 * 清除数据
 */
NoticeInfoDlg.clearData = function () {
    this.noticeInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
NoticeInfoDlg.set = function (key, val) {
    this.noticeInfoData[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
NoticeInfoDlg.get = function (key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
NoticeInfoDlg.close = function () {
    parent.layer.close(window.parent.Notice.layerIndex);
}

NoticeInfoDlg.receiverTypeChange = function(){
	var oldReceiverFilterType = this.noticeInfoData['receiverFilterType'];
	var receiverFilterType = $("#noticeInfoForm input[name='receiverFilterType']:checked").val();
	if(oldReceiverFilterType==receiverFilterType){
		return;
	}
	this.noticeInfoData['receiverFilterType'] = receiverFilterType;
	if(receiverFilterType=="ALL"){
		$(".receiversPicker").hide();
	}else if(receiverFilterType=="USER"){
		$(".receiversPicker").show();
		$(".receiverPicker").hide();
		$(".userPicker").show();
	}else if(receiverFilterType=="DEPT"){
		$(".receiversPicker").show();
		$(".receiverPicker").hide();
		$(".deptPicker").show();
		
	}else if(receiverFilterType=="ROLE"){
		$(".receiversPicker").show();
		$(".receiverPicker").hide();
		$(".rolePicker").show();
		
	}
}

/**
 * 收集数据
 */
NoticeInfoDlg.collectData = function () {
    this.noticeInfoData['content'] = NoticeInfoDlg.editor.txt.html();
    this.set('id').set('title').set("type").set('icon');
    var receiverFilterType = $("#noticeInfoForm input[name='receiverFilterType']:checked").val();
    this.noticeInfoData['receiverFilterType'] = receiverFilterType;
    var checkedNodes =[];
    switch(receiverFilterType){
		case "ALL":
			checkedNodes = [];
			break;
		case "USER":
			checkedNodes = NoticeInfoDlg.userTreeInst.getCheckedNodes(true).filter(n=>n.type=="user");
			break;
		case "DEPT":
			checkedNodes = NoticeInfoDlg.deptTreeInst.getCheckedNodes(true);
			break;
		case "ROLE":
			checkedNodes = NoticeInfoDlg.roleTreeInst.getCheckedNodes(true);
			break;
		default:
			break;
	}
	this.noticeInfoData['receivers'] = checkedNodes.map(n=>n.id);
	
}

/**
 * 验证数据是否为空
 */
NoticeInfoDlg.validate = function () {
    $('#noticeInfoForm').data("bootstrapValidator").resetForm();
    $('#noticeInfoForm').bootstrapValidator('validate');
    return $("#noticeInfoForm").data('bootstrapValidator').isValid();
};

/**
 * 提交添加
 */
NoticeInfoDlg.addSubmit = function () {

    this.clearData();
    this.collectData();

    if (!this.validate()) {
        return;
    }

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/notice/add", function (data) {
        Feng.success("添加成功!");
        window.parent.Notice.table.refresh();
        NoticeInfoDlg.close();
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.noticeInfoData);
    ajax.start();
}

/**
 * 提交修改
 */
NoticeInfoDlg.editSubmit = function () {

    this.clearData();
    this.collectData();

    if (!this.validate()) {
        return;
    }

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/notice/update", function (data) {
        Feng.success("修改成功!");
        window.parent.Notice.table.refresh();
        NoticeInfoDlg.close();
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.type="put";
    ajax.set(this.noticeInfoData);
    ajax.start();
}
$(function () {
    Feng.initValidator("noticeInfoForm", NoticeInfoDlg.validateFields);

    //初始化编辑器
    var E = window.wangEditor;
    var editor = new E('#editor');
    editor.create();
    editor.txt.html($("#contentVal").val());
    NoticeInfoDlg.editor = editor;
    //初始化图标选择器
    $("#icons-dropdown .dropdown-menu li").click(function () {
		$(".selectedIcon").attr("class",$(this).find("span").attr("class")).addClass("selectedIcon");
		$("#icon").val($(this).find("span").attr("data-icon"));
	});
	// 初始化接收者过滤器
    var receiverType = $("#receiverFilterTypeVal").val();
    var receivers = $("#receiversVal").val();
	var receiversArr =[];
	if(!!receivers){
	 receiversArr = JSON.parse(receivers) ;
		
	}
	NoticeInfoDlg.noticeInfoData['receiverFilterType'] = receiverType;
	NoticeInfoDlg.noticeInfoData['receivers'] = receiversArr;
	
	var userId = $("#deptTree").attr("data-deptUserId");
    var ax = new $ax(Feng.ctxPath + "/mgr/view/"+userId, function (data) {
	 // 加载部门树
		var deptId = data.deptid;
		var deptTree = new $ZTree("deptTree", "/dept/tree?deptId="+deptId);
		deptTree.setSettings({
			check: {
				enable: true,
				chkboxType: { "Y": "s", "N": "ps" }
			}
		});
	    deptTree.init();
	    NoticeInfoDlg.deptTreeInst = deptTree.getInstance();
	    if(receiverType=="DEPT" && receiversArr.length>0){
		    receiversArr.forEach(function(receiver){
				NoticeInfoDlg.deptTreeInst.checkNode(NoticeInfoDlg.deptTreeInst.getNodeByParam("id", receiver),true);
			});
	    }
	    // 加载角色树
	    var roleId = data.roleid;
		var roleTree = new $ZTree("roleTree", "/role/roleTreeListByUserId/"+userId);
		roleTree.setSettings({
			check: {
				enable: true,
				chkboxType: { "Y": "s", "N": "ps" }
			}
		});
	    roleTree.init();
	    NoticeInfoDlg.roleTreeInst = roleTree.getInstance();
	    if(receiverType=="ROLE" && receiversArr.length>0){
		    receiversArr.forEach(function(receiver){
			    NoticeInfoDlg.roleTreeInst.checkNode(NoticeInfoDlg.roleTreeInst.getNodeByParam("id", receiver),true);
			});
	    }
	    // 加载用户树
		var userTree = new $ZTree("userTree", "/dept/tree?deptId="+deptId);
		
		userTree.setSettings({
			check: {
				enable: true,
				chkboxType: { "Y": "s", "N": "s" }
			}
		});
	    userTree.init();
	    var userTreeInst = userTree.getInstance();
	    NoticeInfoDlg.userTreeInst = userTreeInst;
	    var deps = userTreeInst.transformToArray(userTreeInst.getNodes());
	    deps.forEach(function(tDept){
		    
			$.getJSON("/mgr/list?deptid="+tDept.id, function (data) {
				var users =data.filter(u=>u.deptid==tDept.id);
				if(users.length>0){
					userTreeInst.addNodes(tDept,0, users.map(function(u) {
						return {
							id: u.id,
							name:u.name,
							pId: u.deptid,
							icon: "/static/img/user.png",
							type:"user",
							checked: receiverType=="USER" && receiversArr.includes(u.id)
						};
					}));
					
				}
			});
	    })
	    
    }, function (data) {
        Feng.error("查询当前用户信息失败");
    });
    ax.type="get";
    ax.start();
    
    
});
